import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
let baseURL = "";
if (process.env.NODE_ENV === "development") {
  // 编译环境
  baseURL = process.env.VUE_APP_BASE_API;
} else {
  if (location.origin == "https://yh.tuomaimai.com") {
    baseURL = "https://supershop.tuomaimai.com";
  } else if (location.origin == "https://yh.simplego.top") {
    baseURL = "https://ht.simplego.top";
  } else {
    baseURL = location.origin;
  }
}

// create an axios instance
const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    const token = getToken();
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  error => {
    // do something with request error
    // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.state !== 100) {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 3 * 1000
      });

      // 106登陆过期 返回登录页;
      if (res.state === 106) {
        // to re-login
        //退出登陆--------------------------------------------
        store.dispatch("user/logout");
      }

      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      const headers = response.headers;
      if (headers.token) {
        store.dispatch("user/reflashToken", headers.token);
      }
      return res;
    }
  },

  error => {
    // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

export default service;
